package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.common.ErrorCode;
import com.graduation.springbootinit.exception.BusinessException;
import com.graduation.springbootinit.mapper.MerchantApplicationMapper;
import com.graduation.springbootinit.model.entity.MerchantApplication;
import com.graduation.springbootinit.model.entity.User;
import com.graduation.springbootinit.service.MerchantApplicationService;
import com.graduation.springbootinit.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class MerchantApplicationServiceImpl extends ServiceImpl<MerchantApplicationMapper, MerchantApplication>
        implements MerchantApplicationService {

    @Resource
    private UserService userService;

    @Override
    public long submitApplication(Long userId, String reason) {
        // 检查是否已经有正在处理的申请
        QueryWrapper<MerchantApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("status", 0)
                .eq("is_delete", 0);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "您已有正在处理的申请");
        }

        // 获取申请用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 创建新的申请记录
        MerchantApplication application = new MerchantApplication();
        application.setUserId(userId);
        application.setApplicantName(user.getUserName());
        application.setReason(reason);
        application.setStatus(0);
        application.setCreateTime(new Date());
        application.setReviewTime(new Date());

        this.save(application);
        return application.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reviewApplication(Long applicationId, Integer status, String reviewComment, Long reviewerId, String reviewerName) {
        MerchantApplication application = this.getById(applicationId);
        if (application == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 只能审核待审核的申请
        if (application.getStatus() != 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该申请已被处理");
        }

        // 更新申请状态
        application.setStatus(status);
        application.setReviewComment(reviewComment);
        application.setReviewerId(reviewerId);
        application.setReviewerName(reviewerName);
        application.setReviewTime(new Date());

        // 如果审核通过，更新用户角色为商户
        if (status == 1) {
            User user = userService.getById(application.getUserId());
            if (user != null) {
                user.setUserRole("merchant");
                userService.updateById(user);
            }
        }

        return this.updateById(application);
    }

    @Override
    public MerchantApplication getUserApplication(Long userId) {
        QueryWrapper<MerchantApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("is_delete", 0)
                .orderByDesc("id")
                .last("LIMIT 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public Page<MerchantApplication> listApplications(long current, long pageSize, Integer status) {
        QueryWrapper<MerchantApplication> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        
        // 如果状态不为null，添加状态筛选条件
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByDesc("create_time");
        return this.page(new Page<>(current, pageSize), queryWrapper);
    }

    @Override
    public Page<MerchantApplication> listPendingApplications(long current, long pageSize) {
        // 直接调用新的 listApplications 方法，传入状态 0（待审核）
        return listApplications(current, pageSize, 0);
    }
}